package com.oceansoft.mobile.econsole.modules.statistic.controller;


import java.io.OutputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.Region;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.oceansoft.mobile.econsole.modules.base.controller.BaseController;
import com.oceansoft.mobile.econsole.modules.base.entity.Query;
import com.oceansoft.mobile.econsole.modules.log.entity.AccessLog;
import com.oceansoft.mobile.econsole.modules.log.entity.StatisticDetail;
import com.oceansoft.mobile.econsole.modules.statistic.service.IStatisticService;
import com.oceansoft.mobile.econsole.task.sms.StringUtil;
@Controller
@RequestMapping("statistic")
public class StatisticController extends BaseController{

	@Resource
	private IStatisticService statisticService;

	@RequestMapping("pv/index")
	public String gotoPVStatisticIndex() {
		return "statistic/pv-index";
	}

	@RequestMapping("uv/index")
	public String gotoUVStatisticIndex() {
		return "statistic/uv-index";
	}
	
	
	@RequestMapping("exportExcel.xls")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response, Query query) {
		//定义行数
		int rowSize = 0;
		HSSFWorkbook wb = new HSSFWorkbook();  
		HSSFCellStyle style = wb.createCellStyle();
		style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直   
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        HSSFSheet sheet = wb.createSheet("应用统计"); 
        for(int i=0;i<6;i++)
        	sheet.setColumnWidth(i, 3500);
        //获取APP软件统计明细数据
		Map<String,Integer> appInfoAll = statisticService.loadAllStatisticAppInfo(query);
		String cellValues[][] = {
				{ "新增下载数", appInfoAll==null?"-":appInfoAll.get("DOWN_NUM")+"", "累计下载数", appInfoAll==null?"-":appInfoAll.get("DOWN_NUM_ALL")+"" },
				{ "新增使用数", appInfoAll==null?"-":appInfoAll.get("USE_NUM")+"", "累计使用数", appInfoAll==null?"-":appInfoAll.get("USE_NUM_ALL")+"" },
				{ "新增注册数", appInfoAll==null?"-":appInfoAll.get("RIG_NUM")+"", "累计注册数", appInfoAll==null?"-":appInfoAll.get("RIG_NUM_ALL")+"" },
				{ "新增用户反馈数",  appInfoAll==null?"-":appInfoAll.get("REPLY_NUM")+"", "累计用户反馈数", appInfoAll==null?"-":appInfoAll.get("REPLY_NUM_ALL")+"" } };
		//初始化第一行,合并第一行的单元格
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 4));
        HSSFRow row = sheet.createRow(rowSize++);
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("APP软件统计明细");
        cell.setCellStyle(style);
		//循环遍历单元格并填充数据
		for(int i=0;i<cellValues.length;i++){
			row = sheet.createRow(rowSize++);
        	for(int j=0;j<4;j++){
        		cell = row.createCell(j);
        		cell.setCellValue(cellValues[i][j]);
        		cell.setCellStyle(style);
        	}
        }
		sheet.addMergedRegion(new CellRangeAddress(5, 5, 0, 4));
		row = sheet.createRow((int)rowSize++);
		cell = row.createCell(0);
		cell.setCellValue("应用统计明细");
		cell.setCellStyle(style);
		//加载应用统计明细数据
		Map<StatisticDetail, ArrayList<StatisticDetail>> tree = loadStatisticData(query);
		for (StatisticDetail key : tree.keySet()) {
			cellValues = new String[tree.get(key).size()+1][];
			if(key.getId() == -1){
				cellValues[0] = new String[]{"","","新增信息数","累计信息数","新增浏览数","累计浏览数"};
			}else if(key.getId() == -3){
				cellValues[0] = new String[]{"","","新增成功数","累计成功数","新增使用数","累计使用数"};
			}else if(key.getId() == -5){
				cellValues[0] = new String[]{"","","新增使用数","累计使用数","新增浏览数","累计浏览数"};
			}else{
				cellValues[0] = new String[]{"","","新增下载数","累计下载数","新增使用数","累计使用数"};
			}
			if(key.getId() == -1 || key.getId() == -3 || key.getId() == -5){
				for(int i=0;i<tree.get(key).size();i++){
					StatisticDetail target = tree.get(key).get(i);
					cellValues[i+1] = new String[]{key.getName(),target.getName(),target.getUseNum()+"",target.getUseNumAll()+"",target.getViewNum()+"",target.getViewNumAll()+""};
				}
			}else{
				for(int i=0;i<tree.get(key).size();i++){
					StatisticDetail target = tree.get(key).get(i);
					cellValues[i+1] = new String[]{key.getName(),target.getName(),target.getDownNum()+"",target.getDownNumAll()+"",target.getViewNum()+"",target.getViewNumAll()+""};
				}
			}
			sheet.addMergedRegion(new CellRangeAddress(rowSize+1, rowSize+tree.get(key).size(), 0, 0));
			//将数据填充到单元格
			for(int i=0;i<cellValues.length;i++){
	        	row = sheet.createRow(rowSize++);
	        	for(int j=0;j<6;j++){
	        		if(cellValues[i][j].equals("null")){
	        			cell = row.createCell(j);
	        			cell.setCellValue("-");
	        			cell.setCellStyle(style);
	        		}else{
	        			cell = row.createCell(j);
	        			cell.setCellValue(cellValues[i][j]);
	        			cell.setCellStyle(style);
	        		}
	        	}
	        }
			
		}
        try{
        	response.setContentType("application/ms-excel");
        	OutputStream out = response.getOutputStream();
        	wb.write(out);  
            out.close();  
        }catch (Exception e){  
            e.printStackTrace();  
        }  
    }
	

	@RequestMapping("index")
	public String gotoStatisticIndex(Model model,Query query) {
		Map<String,Integer> appInfoAll = statisticService.loadAllStatisticAppInfo(query);
		Map<StatisticDetail, ArrayList<StatisticDetail>> tree = loadStatisticData(query);
		model.addAttribute("appInfoAll",appInfoAll);
		model.addAttribute("statistics", tree);
		return "statistic/index";
	}
	
	
	private Map<StatisticDetail, ArrayList<StatisticDetail>> loadStatisticData(Query query){
		List<StatisticDetail> details = statisticService.loadStatisticDeatil(query);
		Map<StatisticDetail, ArrayList<StatisticDetail>> tree = new LinkedHashMap<StatisticDetail, ArrayList<StatisticDetail>>();
		//遍历统计数据集合
		for (StatisticDetail statistic : details) {
			//如果是父节点则加入到hashmap
			if (statistic.getPid() == 0) {
				tree.put(statistic, new ArrayList<StatisticDetail>());
			} else {
				//遍历map的key，如果key的id和当前对象的父id相等则将当前对象放到key对应的value集合中
				for (StatisticDetail key : tree.keySet()) {
					if(key.getId() == statistic.getPid()){
						tree.get(key).add(statistic);
					}
				}
			}
		}
		return tree;
	}
	
}
